// SFTP 前端交互（本地API占位实现，后续可接入远程SFTP）
(function(){
  let currentPath = '/';
  let selectedItem = null; // { name, path, is_dir, size }
  let currentSessionId = null; // 后端SFTP会话ID

  const $modal = document.getElementById('sftpModal');
  const $tree = document.getElementById('sftp-tree');
  const $preview = document.getElementById('sftp-preview');
  const $previewEmpty = document.getElementById('sftp-preview-empty');
  const $currentPath = document.getElementById('sftp-current-path');

  const $btnUpload = document.getElementById('sftp-upload-btn');
  const $btnDownload = document.getElementById('sftp-download-btn');
  const $btnRename = document.getElementById('sftp-rename-btn');
  const $btnDelete = document.getElementById('sftp-delete-btn');
  const $btnGoUp = document.getElementById('sftp-go-up-btn');
  const $btnRefresh = document.getElementById('sftp-refresh-btn');
  const $fileInput = document.getElementById('sftp-upload-input');

  function formatSize(bytes){
    const b = Number(bytes || 0);
    const KB = 1024;
    const MB = KB * 1024;
    const GB = MB * 1024;
    if (b >= GB) return (b / GB).toFixed(2) + ' GB';
    if (b >= MB) return (b / MB).toFixed(2) + ' MB';
    if (b >= KB) return (b / KB).toFixed(2) + ' kb';
    return b + ' B';
  }

  function setToolbarState() {
    const hasSelection = !!selectedItem;
    $btnDownload.disabled = !hasSelection || !!(selectedItem && selectedItem.is_dir);
    $btnRename.disabled = !hasSelection;
    $btnDelete.disabled = !hasSelection;
  }

  function joinPath(base, name){
    if(base.endsWith('/')) return base + name;
    return base + '/' + name;
  }

  function parentPath(path){
    if (!path || path === '/') return '/';
    const parts = path.split('/').filter(Boolean);
    parts.pop();
    return '/' + parts.join('/');
  }

  async function apiList(path){
    const resp = await fetch(`/api/sftp/list?session_id=${encodeURIComponent(currentSessionId)}&path=${encodeURIComponent(path || '/')}`);
    if(!resp.ok) throw new Error('列表获取失败');
    return resp.json();
  }

  async function apiRead(path){
    const resp = await fetch(`/api/sftp/read?session_id=${encodeURIComponent(currentSessionId)}&path=${encodeURIComponent(path)}`);
    if(!resp.ok) throw new Error('读取文件失败');
    const data = await resp.json();
    return data.content || '';
  }

  async function apiDelete(path){
    const resp = await fetch('/api/sftp/delete', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({ session_id: currentSessionId, path })
    });
    if(!resp.ok) throw new Error('删除失败');
  }

  async function apiRename(path, new_name){
    const resp = await fetch('/api/sftp/rename', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({ session_id: currentSessionId, path, new_name })
    });
    if(!resp.ok) throw new Error('重命名失败');
  }

  async function apiUpload(destPath, filename, base64){
    const resp = await fetch('/api/sftp/upload', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({ session_id: currentSessionId, path: destPath, filename, content_base64: base64 })
    });
    if(!resp.ok) throw new Error('上传失败');
  }

  async function apiDownload(path){
    const resp = await fetch(`/api/sftp/download?session_id=${encodeURIComponent(currentSessionId)}&path=${encodeURIComponent(path)}`);
    if(!resp.ok) throw new Error('下载失败');
    const blob = await resp.blob();
    const a = document.createElement('a');
    const url = URL.createObjectURL(blob);
    a.href = url;
    const name = path.split('/').filter(Boolean).pop() || 'download';
    a.download = name;
    a.click();
    URL.revokeObjectURL(url);
  }

  function renderTree(list){
    $tree.innerHTML = '';
    list.forEach(item => {
      const li = document.createElement('li');
      li.className = 'list-group-item d-flex justify-content-between align-items-center sftp-item';
      li.dataset.name = item.name;
      li.dataset.path = item.path;
      li.dataset.isDir = item.is_dir ? '1' : '0';
      li.innerHTML = `
        <div class="d-flex align-items-center">
          <i class="fa ${item.is_dir ? 'fa-folder' : 'fa-file-o'} me-2"></i>
          <span class="sftp-name">${item.name}</span>
        </div>
        <span class="badge bg-light text-muted">${item.is_dir ? '目录' : formatSize(item.size)}</span>
      `;
      // 单击选中
      li.addEventListener('click', () => {
        document.querySelectorAll('#sftp-tree .list-group-item').forEach(el => el.classList.remove('active'));
        li.classList.add('active');
        selectedItem = item;
        setToolbarState();
        // 如果是文件，预览
        if(!item.is_dir){
          apiRead(item.path).then(text => {
            $preview.textContent = text;
            $preview.classList.remove('d-none');
            $previewEmpty.classList.add('d-none');
          }).catch(() => {
            $preview.textContent = '无法预览该文件';
            $preview.classList.remove('d-none');
            $previewEmpty.classList.add('d-none');
          });
        } else {
          // 目录则清空预览提示
          $preview.classList.add('d-none');
          $previewEmpty.classList.remove('d-none');
        }
      });
      // 双击打开目录或预览文件
      li.addEventListener('dblclick', () => {
        if(item.is_dir){
          loadDirectory(item.path);
        } else {
          apiRead(item.path).then(text => {
            $preview.textContent = text;
            $preview.classList.remove('d-none');
            $previewEmpty.classList.add('d-none');
          }).catch(() => {
            $preview.textContent = '无法预览该文件';
            $preview.classList.remove('d-none');
            $previewEmpty.classList.add('d-none');
          });
        }
      });
      $tree.appendChild(li);
    });
  }

  async function loadDirectory(path){
    try {
      const list = await apiList(path);
      currentPath = path || '/';
      $currentPath.textContent = currentPath;
      selectedItem = null;
      setToolbarState();
      renderTree(list);
      // 清空预览
      $preview.classList.add('d-none');
      $previewEmpty.classList.remove('d-none');
    } catch(e){
      console.error('加载目录失败', e);
      $tree.innerHTML = '<div class="text-center text-danger p-2">加载目录失败</div>';
    }
  }

  // 创建SFTP会话
  async function ensureSftpSession(){
    if (currentSessionId != null) return;
    // 从SSH连接表单读取当前选定服务器信息
    const hostEl = document.querySelector('#ssh-host');
    const portEl = document.querySelector('#ssh-port');
    const userEl = document.querySelector('#ssh-username');
    const passEl = document.querySelector('#ssh-password');
    const hostname = (hostEl && hostEl.value || '').trim();
    const port = parseInt((portEl && portEl.value || '22'), 10) || 22;
    const username = (userEl && userEl.value || '').trim();
    const password = (passEl && passEl.value || '').trim();
    if (!hostname || !username) throw new Error('请先在SSH面板选择服务器并填写凭据');
    const resp = await fetch('/api/sftp/session', {
      method: 'POST', headers: {'Content-Type':'application/json'},
      body: JSON.stringify({ hostname, port, username, password })
    });
    if(!resp.ok) throw new Error('创建SFTP会话失败');
    const data = await resp.json();
    currentSessionId = data.session_id;
  }

  // 事件绑定
  if($modal){
    $modal.addEventListener('show.bs.modal', async () => {
      try {
        await ensureSftpSession();
        await loadDirectory('/');
      } catch(e){
        console.error(e);
        $tree.innerHTML = '<div class="text-center text-danger p-2">无法创建SFTP会话，请检查SSH凭据</div>';
      }
    });
  }

  if($btnGoUp){
    $btnGoUp.addEventListener('click', () => {
      loadDirectory(parentPath(currentPath));
    });
  }

  if($btnRefresh){
    $btnRefresh.addEventListener('click', () => loadDirectory(currentPath));
  }

  if($btnDelete){
    $btnDelete.addEventListener('click', async () => {
      if(!selectedItem) return;
      if(!confirm(`确认删除 ${selectedItem.name} ?`)) return;
      try {
        await apiDelete(selectedItem.path);
        await loadDirectory(currentPath);
      } catch(e){ console.error(e); alert('删除失败'); }
    });
  }

  if($btnRename){
    $btnRename.addEventListener('click', async () => {
      if(!selectedItem) return;
      const newName = prompt('输入新名称', selectedItem.name);
      if(!newName || newName === selectedItem.name) return;
      try {
        await apiRename(selectedItem.path, newName);
        await loadDirectory(currentPath);
      } catch(e){ console.error(e); alert('重命名失败'); }
    });
  }

  if($btnUpload && $fileInput){
    $btnUpload.addEventListener('click', () => $fileInput.click());
    $fileInput.addEventListener('change', async () => {
      const file = $fileInput.files && $fileInput.files[0];
      if(!file) return;
      try {
        const reader = new FileReader();
        reader.onload = async () => {
          // result is ArrayBuffer
          const arr = new Uint8Array(reader.result);
          // convert to base64
          let binary = '';
          const chunk = 0x8000;
          for(let i=0;i<arr.length;i+=chunk){
            binary += String.fromCharCode.apply(null, arr.subarray(i, i+chunk));
          }
          const base64 = btoa(binary);
          await apiUpload(currentPath, file.name, base64);
          await loadDirectory(currentPath);
          $fileInput.value = '';
        };
        reader.readAsArrayBuffer(file);
      } catch(e){ console.error(e); alert('上传失败'); }
    });
  }

  if($btnDownload){
    $btnDownload.addEventListener('click', () => {
      if(!selectedItem || selectedItem.is_dir) return;
      apiDownload(selectedItem.path).catch(e => { console.error(e); alert('下载失败'); });
    });
  }

  // 暴露初始化入口（与既有initSSH并行）
  window.initSFTP = function(){
    setToolbarState();
  };
})();